package com.petecapra.cashflow.model.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class CashflowManager<T> {
			
	@Autowired protected SessionFactory sf;
	private Class<T> clazz;
	
	public CashflowManager(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	public void save(T t) {		
		if (sf.getCurrentSession().contains(t)) {
			sf.getCurrentSession().merge(t);
		} else {
			sf.getCurrentSession().save(t);
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public T findById(long id) {
		return (T) sf.getCurrentSession().get(clazz, id);
	}
	
	public void delete(T t) {
		sf.getCurrentSession().delete(t);
		sf.getCurrentSession().flush();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		Criteria criteria = sf.getCurrentSession().createCriteria(clazz);
		return criteria.list();
	}
	
	protected Criteria getCriteria() {
		return sf.getCurrentSession().createCriteria(clazz);
	}

}